package com.jia.leetCode;


/**
 * 对于字符串 S 和 T，只有在 S = T + ... + T（T 与自身连接 1 次或多次）时，我们才认定 “T 能除尽 S”。

返回字符串 X，要求满足 X 能除尽 str1 且 X 能除尽 str2。

 

示例 1：

输入：str1 = "ABCABC", str2 = "ABC"
输出："ABC"
示例 2：

输入：str1 = "ABABAB", str2 = "ABAB"
输出："AB"
示例 3：

输入：str1 = "LEET", str2 = "CODE"
输出：""
 

提示：

1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] 和 str2[i] 为大写英文字母
在真实的面试中遇到过这道题？

 * 
 * @author Administrator
 *
 */
public class Pro1071 {
	public String gcdOfStrings(String str1, String str2) {
		if(str1 == null || str2 == null) return "";
		String longStr = str1.length() > str2.length()? str1 : str2;
		String shortStr = str1.length() > str2.length()? str2 : str1;
		while(longStr.length() != shortStr.length()) {
			if(longStr.indexOf(shortStr) == 0) {
				String tempStr = longStr.substring(shortStr.length(), longStr.length());
				longStr = tempStr.length() > shortStr.length()? tempStr : shortStr;
				shortStr = tempStr.length() > shortStr.length()? shortStr : tempStr;
			}else {
				return "";
			}
		}
		if(longStr.equals(shortStr)) {
			return longStr;
		}
		return "";
	}
	//暴力
	public String gcdOfStrings2(String str1, String str2) {
		if(str1 == null || str2 == null) return "";
		String longStr = str1.length() > str2.length()? str1 : str2;
		String shortStr = str1.length() > str2.length()? str2 : str1;
		StringBuilder sb = new StringBuilder();
		String shortTemp = shortStr;
		String longTemp = longStr;
		String result ="";
		for(int i = 0; i < shortStr.length(); i++) {
			sb.append(shortStr.charAt(i));
			shortTemp = shortStr;
			longTemp = longStr;
			if(shortStr.replaceAll(sb.toString(), "").equals("") && longStr.replaceAll(sb.toString(), "").equals("")) {
				result = sb.toString();
			}
		}
		return result;
	}
	
	
	//辗转相除
    public String gcdOfStrings3(String str1, String str2) {
		if(!(str1 + str2).equals(str2+str1)) return "";
        return str1.substring(0, gcb(str1.length(), str2.length()));
	}
    private int gcb(int a, int b) {
        return b == 0? a : gcb(b, a % b);
    }
}
